<template>
  <div class="app-container">
    <el-card class="box-card">
      <el-form ref="form" :model="form" label-width="80px">
        <el-form-item label="头像">
          <el-upload
            class="avatar-uploader"
            :action="uploadUrl"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="form.avatar" :src="form.avatar" class="avatar" alt="">
            <i v-else class="el-icon-plus avatar-uploader-icon" />
          </el-upload>
        </el-form-item>
        <el-form-item label="名称">
          <el-input v-model="form.name" placeholder="请输入用户名称" />
        </el-form-item>
        <el-form-item label="邮箱">
          <el-input v-model="form.email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item v-if="!form.userId" label="密码">
          <el-input
            v-model="form.password"
            auto-complete="new-password"
            placeholder="请输入密码"
            type="password"
            show-password
          />
        </el-form-item>
        <el-form-item label="学校">
          <el-input v-model="form.school" placeholder="请输入学校" />
        </el-form-item>
        <el-form-item label="籍贯">
          <el-cascader
            v-model="selectedOptions"
            size="large"
            :options="regionData"
            filterable
            @change="handleChange"
          />
        </el-form-item>
        <el-form-item label="性别">
          <el-select v-model="form.sex" placeholder="请选择" filterable>
            <el-option key="0" :value="0" label="男" />
            <el-option key="1" :value="1" label="女" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" size="small" @click="onSubmit">立即保存</el-button>
          <el-button size="small" @click="cancel">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import md5 from 'js-md5'
// eslint-disable-next-line no-unused-vars
import { provinceAndCityData, CodeToText, TextToCode } from 'element-china-area-data'
import { createUser, getUser, updateUser } from '@/api/user'

const defaultSettings = require('@/settings.js')
export default {
  data() {
    return {
      regionData: provinceAndCityData,
      selectedOptions: [],
      imageUrl: '',
      uploadUrl: defaultSettings.uploadUrl,
      form: {
        userId: '',
        name: '',
        password: '',
        avatar: '',
        email: '',
        school: '',
        sex: '',
        provString: []
      }
    }
  },
  created() {
    if (this.$route.query.userId) {
      this.form.userId = this.$route.query.userId
      this.getUser()
    }
  },
  methods: {
    cancel() {
      this.$router.push('/user')
    },
    getUser() {
      getUser({ userId: this.form.userId }).then(res => {
        if (res.code === 200) {
          this.form.name = res.data.nickname
          this.form.avatar = res.data.avatar
          this.form.password = res.data.password
          this.form.email = res.data.email
          this.form.school = res.data.school
          this.form.sex = res.data.sex
          this.form.provString = [res.data.prov, res.data.city]
          this.selectedOptions = [TextToCode[res.data.prov]['code'], TextToCode[res.data.prov][res.data.city]['code']]
          // eslint-disable-next-line no-sequences
        } else {
          this.$message.error('网络错误')
        }
      })
    },
    onSubmit() {
      const form = {
        userId: this.form.userId,
        nickname: this.form.name,
        password: md5(this.form.password),
        email: this.form.email,
        school: this.form.school,
        sex: this.form.sex,
        avatar: this.form.avatar,
        prov: this.form.provString[0],
        city: this.form.provString[1]
      }
      if (form.userId) {
        // eslint-disable-next-line no-undef
        updateUser(form).then(res => {
          if (res.code === 200) {
            this.$message.success('保存成功')
            this.$router.push('/user')
          } else {
            this.$message.error('网络错误')
          }
        })
      } else {
        // eslint-disable-next-line no-undef
        createUser(form).then(res => {
          if (res.code === 200) {
            this.$message.success('保存成功')
            this.$router.push('/user')
          } else {
            this.$message.error('网络错误')
          }
        })
      }
    },
    handleChange() {
      this.form.provString = []
      for (let i = 0; i < this.selectedOptions.length; i++) {
        this.form.provString.push(CodeToText[this.selectedOptions[i]])
      }
      console.log(this.selectedOptions)
    },
    handleAvatarSuccess(res, file) {
      if (res.code === 200) {
        this.form.avatar = res.data
      } else {
        this.$message.error('网络错误')
      }
    },
    beforeAvatarUpload(file) {
      const imageFile = ['image/jpeg', 'image/png']
      const isJPG = imageFile.indexOf(file.type)
      const isLt2M = file.size / 1024 / 1024 < 10
      if (isJPG < 0) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 10MB!')
      }
      return isJPG && isLt2M
    }
  }
}
</script>
